package com.lbh.graphics;

import com.jogamp.opengl.GL2;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/***
 * project:JRuntime
 * package:com.lbh.graphics
 *
 * @author user:lenovo QQ:1601078366
 * @date 2021/10/21 22:23
 * @version V1.0
 */
public class GLUtils {

    public static List<String> getLines(String res){
        ArrayList<String> list = new ArrayList<>();
        Scanner scanner = new Scanner(GLUtils.class.getResourceAsStream(res));
        while (scanner.hasNextLine()){
            list.add(scanner.nextLine());
        }
        return list;
    }

    public static int initGLShader(GL2 gl, int stage, String source){
        int shader = gl.glCreateShader(stage);
        List<String> list = getLines(source);
        compile(gl, list, shader);
        return shader;
    }

    public static void printShaderLog(GL2 gl, int shader){
        int[] val = new int[1];
        gl.glGetShaderiv(shader, GL2.GL_COMPILE_STATUS, val, 0);
        if (val[0] == GL2.GL_TRUE){
            return;
        }
        gl.glGetShaderiv(shader, GL2.GL_INFO_LOG_LENGTH, val, 0);
        if (val[0] > 0){
            byte[] info = new byte[val[0]];
            gl.glGetShaderInfoLog(shader, val[0], val, 0, info, 0);
            System.out.println("Shader Compilation Error:");
            System.out.println(new String(info, Charset.defaultCharset()));
        }
    }

    public static void printProgramLog(GL2 gl, int program){
        int[] val = new int[1];
        gl.glGetProgramiv(program, GL2.GL_COMPILE_STATUS, val, 0);
        if (val[0] == GL2.GL_TRUE){
            return;
        }
        gl.glGetProgramiv(program, GL2.GL_INFO_LOG_LENGTH, val, 0);
        if (val[0] > 0){
            byte[] info = new byte[val[0]];
            gl.glGetProgramInfoLog(program, val[0], val, 0, info, 0);
            System.out.println("Program Linkage Error:");
            System.out.println(new String(info, Charset.defaultCharset()));
        }
    }

    static void compile(GL2 gl, List<String> code, int shader) {
        String[] lines = new String[code.size()];
        code.toArray(lines);
        for (int i = 0; i < lines.length; i++) {
            lines[i] += "\n";
        }
        gl.glShaderSource(shader, lines.length, lines, null);
        gl.glCompileShader(shader);
        printShaderLog(gl, shader);
    }
}
